package com.example.springadminclient.configuration;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

@Configuration
public class MetricsConfig {

    private final Environment env;

    @Bean
    public Counter customCounter(MeterRegistry registry) {

        return registry.counter(getMyEnvVar());
    }


    @Autowired
    public MetricsConfig(Environment env) {
        this.env = env;
    }

    public String getMyEnvVar() {
        System.out.println("======"+env.getProperty("serverAddress"));
        return env.getProperty("serverAddress");
    }

    public String getFirstNonLoopbackAddress() {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                if (!networkInterface.isUp() || networkInterface.isLoopback() || networkInterface.isVirtual())
                    continue;

                Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    InetAddress inetAddress = inetAddresses.nextElement();
                    if (inetAddress.isSiteLocalAddress()) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            throw new RuntimeException("Error while fetching network interfaces.", e);
        }
        return null;
    }
}